package cn.sanli.manage.service.impl;

import cn.sanli.manage.mapper.data1.UserMapper;
import cn.sanli.manage.pojo.dto.Login.LoginUserDTO;
import cn.sanli.manage.pojo.vo.UserMessage;
import cn.sanli.manage.security.UserDetail;
import cn.sanli.manage.service.UserService;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    public UserMapper userMapper;

    @Value("${security.jwt}")
    private String signature;

    @Value("${security.EXPIRATION}")
    private String expiration;


    @Override
    public String login(LoginUserDTO loginUserDTO) {
        log.debug("开始在Service层处理用户登录请求，输入的登录信息为：{}",loginUserDTO);
        Authentication authentication=new UsernamePasswordAuthenticationToken(
                loginUserDTO.getNum(), loginUserDTO.getPassword()
        );
       Authentication authenticate = authenticationManager.authenticate(authentication);
        log.debug("通过的认证信息为:{}",authenticate);

        //从认证结果中获取需要的数据
        UserDetail userDetail = (UserDetail)authenticate.getPrincipal();
        Map<String,Object> claims=new HashMap<>();
        claims.put("num",userDetail.getUsername());
        claims.put("centerId",userDetail.getCenterId());
        claims.put("deptId",userDetail.getDeptId());
        claims.put("rol",userDetail.getRoleId());
        String s = JSON.toJSONString(userDetail.getAuthorities());
        claims.put("authoritiesJsonString",s);
        claims.put("userName",userDetail.getUserName());
        //生成jwt数据
        String jwt = jwt(claims);
        log.debug("Spring Security框架已验证通过,生成的jwt数据是{}",jwt);
        return jwt;
    }

    @Override
    public UserMessage message(String num) {
        //查询登录用户的基本信息
        UserMessage userMessage = userMapper.selectMessage(num);
        String s = userMapper.selectRegion(userMessage.getCenter_id());
        userMessage.setCenterName(s);
        return userMessage;
    }

    String jwt(Map<String,Object> map){
        long l = Long.parseLong(expiration);
        String jwt= Jwts.builder()
                .setHeaderParam( "alg", "HS256")
                .setHeaderParam("typ","JWT")
                .setClaims(map)
                .setExpiration(new Date(System.currentTimeMillis()+l))
                .signWith(SignatureAlgorithm.HS256,signature)
                .compact();
        return jwt;
    };


}
